<template>
  <div :id="id" :class="className" :style="{height:height,width:width}" />
</template>

<script>
import resize from './mixins/resize';

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: String,
      default: '200px'
    },
    options: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    };
  },
  watch: {
    options: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.chart.dispose();
          this.chart = null;
          this.initChart(this.id, newVal);
        } else {
          this.chart.dispose();
          this.chart = null;
          this.initChart(this.id, oldVal);
        }
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart(this.id, this.options);
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart(id, options) {
      this.chart = this.$echarts.init(document.getElementById(id));
      this.chart.setOption(options);
      this.chart.on('dataZoom', param => {
        const chartsMap = this.chart._chartsMap;
        // eslint-disable-next-line prefer-const
        let zoomData = [];
        for (const s in chartsMap) {
          if (chartsMap.hasOwnProperty(s)) {
            const map = chartsMap[s];
            const dataAll = map['_data'];
            const indexArr = dataAll['_approximateExtent']['x'];
            const Max = parseInt(indexArr[1]);
            const Min = parseInt(indexArr[0]);
            const data = dataAll['_rawData']['_data'];
            const name = dataAll['_idList'];
            const dataName = map['__model']['name'];

            // eslint-disable-next-line prefer-const
            let obj = {
              name: dataName,
              data: []
            };
            for (let i = Min; i <= Max; i++) {
              // eslint-disable-next-line prefer-const
              let o = {
                name: '',
                data: 0
              };
              o.name = name[i];
              o.data = data[i];
              obj.data.push(o);
            }
            zoomData.push(obj);
          }
        }
        this.$emit('dataZoom', zoomData);
      });
    }
  }
};
</script>
